# coding:utf-8
from flask import Flask, request, render_template, Response
import json
from werkzeug.datastructures import ImmutableMultiDict
from utils import *

from BaseClass import *
from BaseDao import *

import json

app = Flask(__name__, static_folder="static")


@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


# 首页
@app.route('/', methods=['POST', "GET"])
def index():
    return render_template("index.html")


# 添加方剂
@app.route('/addPrescription', methods=['POST', "GET"])
def addPrescription():
    if request.method == 'GET':
        flag = 5
        return render_template('Addprescription.html', **{"flag": flag})

    para_dict = request.form.to_dict()  # 获取所有参数
    print(para_dict)
    para = [para_dict[i] for i in para_dict]  # 提取参数
    # print("pase",para)
    #
    # for word in para_dict['major'].split("，"):
    #     sp = chineseToSpell(word)
    #     print([sp, word])
    #     ple = Participle()
    #     ple.init(sp, word)
    #     addData(ple)

    p = Prescription()  # 实例化方剂存储类
    p.init(*para)  # 初始化传参
    flag = addData(p)  # 添加数据  flag：true、false
    return render_template('Addprescription.html', **{"flag": flag})


'''查看所有方剂'''


@app.route("/findAllPrescription")
def findAllPrescription():
    all_list = findallfj()
    return returnPara('200', "succ", all_list)


'''根据id查询'''


@app.route("/findPrescriptionByid", methods=["POST"])
def findPrescriptionByid():
    id = request.args.get("id")
    try:
        data = findPrescriptionById(id)
        return returnPara("200", "succ", [data])
    except:
        return returnPara("500", "faild", "")


'''修改方剂'''


@app.route("/modifyPrescription", methods=["POST"])
def modifyPrescription():
    para_dict = request.form.to_dict()
    print(para_dict)
    para = [para_dict[i] for i in para_dict]

    flag = modfyPrescription(para_dict['id'], *para)
    return returnPara('200', "succ", {"falg": flag})


'''
模糊查询
'''


@app.route("/searKeyWordBySpell", methods=['POST', "GET"])
def searKeyWordBySpell():
    key = request.args.get('key')

    if key == None:
        return returnPara(2000, "")

    res_dict = findWordBySpell(key)
    print("=================", type(res_dict))
    t = {"code": 200, "msg": "succ", "data": res_dict}
    return Response(json.dumps(t), mimetype='application/json')


'''
添加症状类别
'''


@app.route("/addSymptomType", methods=["POST"])
def addSymptomType():
    name = request.values.get("name")
    print(name)
    if name == None:
        return {"code": 200, "msg": "failed", "data": ""}
    sy = symptomType()
    sy.init(name)
    print(sy)
    flag = addData(sy)
    if flag:
        return {"code": 200, "msg": "succ", "data": ""}
    else:
        return {"code": 200, "msg": "failed", "data": ""}


'''查询疾病类型'''


@app.route("/findSyType", methods=["GET"])
def fSyType():
    data = findSyType()
    return returnPara(200, "succ", data)


'''
添加症状类别
'''


@app.route("/addsymptomDetails", methods=["POST"])
def addsymptomDetails():
    name = request.values.get("name")
    print(name)
    if name == None:
        return {"code": 200, "msg": "failed", "data": ""}
    sy = symptomType()
    sy.init(name)
    print(sy)
    flag = addData(sy)
    if flag:
        return {"code": 200, "msg": "succ", "data": ""}
    else:
        return {"code": 200, "msg": "failed", "data": ""}


@app.route('/get_data')
def hello_world():
    data = request.args.get('data')
    text = {"ehz": "恶寒重", "frq": "发热轻", "wh": "无汗", "tt": "头痛", "zjst": "肢节酸痛", "bssz": "鼻塞声重", "bypt": "鼻痒喷嚏",
            "slqt": "时流清涕",
            "yy": "咽痒", "ks": "咳嗽", "txbsb": "痰稀薄色白"}
    key = ['tt', 'tt', 'fs', 'fs', 'ks', 'ks', 'fr', 'fr']
    print(data)
    value = ['疼痛', '头痛', '发酸', '发烧', '咳嗽', '瞌睡', '发热', '肺热']
    res = []
    for i in range(len(key)):
        if data == key[i]:
            res.append(value[i])
    return str(res)


@app.route("/disease", methods=['post'])
def disease():
    # data = request.args.get('data')
    data = request.get_json(force=True)
    print(data['msg'])
    res = {
        "type": "风寒束症",
        "方剂": [{"name": "荆防达表汤", "id": "12"}, {"name": "荆防败毒散", "id": "13"}],
        "治法": ["辛温表解"],
        "主症": ["恶寒重", "发热", "无汉", "头痛", "肢节酸痛", "鼻塞声重", "鼻痒喷嚏", "时流清鼻"],
        "加减": "若表寒重，头身痛，憎寒发热，无汗者，配麻黄、桂枝;若表湿较重，肢体酸痛，头重头胀，身热不扬者，加羌活、独活，或用羌活胜湿汤。"
    }
    return res


@app.route("/get_drug/<id>")
def get_drug(id):
    print(id)
    return {"msg": "[组成]柴胡、前胡、川弯、积壳、芜活、独活、获苓、桔梗、人参、甘草。"
                   "[方收]人参败毒获苓草，积桔柴前羌独等，溥荷少许姜三片，四时感冒有奇功。"
                   "[用法]上为粗末， 每服二钱，加生姜、薄荷各少许，水煎去幸热服。亦可作汤剂，人生姜、薄荷各少许水煎服，用量按原方比例酌减。"
                   "[功用]散寒祛湿，益气解表。"
                   "[主治]气虚，外感风寒湿表证。憎寒壮热，头项强痛，肢体酸痛，无汗，鼻塞声重，咳嗽有痰，胸膈痞满，舌淡苔白，脉浮而按之无力。"
                   "[配伍意义]羌活、独活为君，发散风寒，除湿止痛。川芎行气活血，祛风;柴胡解肌透邪，行气。二药为臣。桔梗宣肺利膈，枳壳理气宽中，前胡化痰以止咳，茯苓渗湿以消痰。四药为佐。 生姜、薄荷助解表之力:甘草调和药性，益气和中，共为佐使。人参亦属佐药，与甘草相配，益气扶正。喻嘉言用本方治疗外邪陷里而成之痢疾，意即疏散表邪，表气疏通，里滞亦除，其期自止。称“逆流挽舟”法。",
            "drug": "柴胡、前胡、川弯、积壳、芜活、独活、获苓、桔梗、人参、甘草"
            }


@app.route("/book/add_book", methods=['POST'])
def insert_book():
    """添加书籍"""

    book = Book()
    book.init(request.values['book_name'])
    return judge_status(insert_data(book))


@app.route("/book/add_chapter", methods=['POST'])
def insert_chapter():
    """添加章节"""
    chapter = Chapter()
    chapter.init(request.values['book_id'], request.values['chapter_name'])
    return judge_status(insert_data(chapter))


@app.route("/book/add_content", methods=['POST'])
def insert_content():
    """添加内容"""
    content = Content()
    content.init(request.values['chapter_id'], request.values['content_name'], request.values['content_txt'])
    return judge_status(insert_data(content))


@app.route("/book/get_book", methods=['GET'])
def get_book():
    return judge_status(get_book_list())


@app.route("/book/get_chapter", methods=['GET'])
def get_chapter():
    book_id = request.args.get("book_id")
    return judge_status(get_chapter_by_book_id(book_id))


@app.route("/book/get_content", methods=['GET'])
def get_content():
    chapter_id = request.args.get("chapter_id")
    return judge_status(get_content_by_chapter_id(chapter_id))


@app.route("/cure/add_symptom", methods=['POST'])
def add_symptom():
    """插入症状"""
    symptom = Symptom()
    symptom.init(request.values['symptom_name'])
    return judge_status(insert_data(symptom))


@app.route("/cure/update_symptom")
def update_symptom():
    """跟新症状"""
    symptom = Symptom()
    symptom.init(request.values['id'], request.values['symptom_name'])
    return judge_status(update_symptom_by_id(symptom))


@app.route("/cure/get_symptom")
def get_symptom():
    """获取症状列表"""
    print(request.values)
    return judge_status(get_symptom_list())


@app.route("/cure/add_treat", methods=['POST'])
def add_treat():
    treat = Treat()
    ple = Participle()
    type = request.values['treat_type']
    for word in request.values['treat_main'].split("，"):
        sp = chineseToSpell(word)
        print([sp, word])
        ple = Participle()
        ple.init(sp, word, type)
        addData(ple)
    treat.init(request.values['symptom_id'], request.values['symptom_name'],
               request.values['treat_main'], request.values['treat_method'],
               request.values['treat_drug'], request.values['treat_add_sub'], request.values['treat_type'])

    return judge_status(insert_data(treat))


@app.route("/cure/update_treat")
def update_treat():
    treat = Treat()

    treat.update(request.values['id'], request.values['symptom_id'], request.values['symptom_name'],
                 request.values['treat_main'], request.values['treat_method'],
                 request.values['treat_drug'], request.values['treat_add_sub'], request['treat_type'])
    return judge_status(update_treat_by_id(treat))


@app.route("/cure/get_treat")
def get_treat():
    return judge_status(get_treat_by_symptom_id(request.values['symptom_id']))


if __name__ == '__main__':
    app.run(debug=True, port=80, host="0.0.0.0")
